// app.js
let request = require('./utils/request.js')
let fly = require('./utils/fly-http.js')
const AV = require('./lib/av-core-min')
require('./utils/leancloud-init')
App({
    onLaunch() {
        // 尝试提取本地存储用户信息
        try {
            var value = wx.getStorageSync('userInfo')
            if (value) {
                console.log(value);
                this.globalData.userInfo = value
                // Do something with return value
            }
        } catch (e) {
            console.log('本地用户信息提取失败');
            // Do something when catch error
        }
    },
    globalData: {
        userInfo: null
    },
    ...request, //全局挂载通用异步请求方法
    fly,
    handleLogin(){
        wx.getUserProfile({
          desc: '请授权以便为您提供VIP服务',
          success:(info)=>{
            // console.log(info.userInfo); //【1】微信用户头像、昵称等信息 【可选】
            let {userInfo} = info
            AV.User.loginWithMiniApp().then(user => { //【2】使用后端接口授权登录
                let {openid} = user.attributes.authData.lc_weapp //授权登录成功，得到用户的openid等信息
                console.log(user);
                let {fly} = getApp()
                fly.config.headers['X-LC-Session'] = user._sessionToken  
                fly.put(`/users/${user.id}`,userInfo).then(res=>{//【3】更新用户表，必须携带session
                    // console.log(res);
                    userInfo.userid = user.id
                    userInfo.openid = openid
                    this.globalData.userInfo = userInfo //全局存储用户信息
                    wx.setStorage({ //本地存储用户信息
                        key:'userInfo',
                        data:userInfo
                    })
                    // this.setData({userInfo})
                })
            }).catch(console.error);
          },
          fail:(err)=>{
              wx.showToast({
                title: '很遗憾不能为您提供VIP服务',
                icon:'none'
              })
          }
        })
    },
})